import shutil
import os
import subprocess
import time

def Build_HotDll():
    # 定义Unity路径和项目路径
    unity_path = r"D:\Unity Hub\Hub_Install\2023.2.20f1c1\Editor\Unity.exe"
    project_path = r"D:\Project\HotFix_Test\HybridCLR_Project"

    # 构造命令行参数
    command = [
        unity_path,
        "-batchmode",
        "-nographics",
        "-projectPath", project_path,
        "-executeMethod", "AutoCompileHybridCLR.AutoCompile",
        "-logFile", os.path.join(project_path, "compile_log.txt"),
        "-quit"
    ]

    # 执行命令
    print("开始编译HybridCLR DLL...")
    result = subprocess.run(command, capture_output=True, text=True)

    # 检查执行结果
    if result.returncode == 0:
        print("HybridCLR DLL编译成功！")
        return True
    else:
        print("编译失败，请查看日志文件 compile_log.txt")
        os.system(f"explorer.exe {project_path}")
        print(result.stderr)
        return False



def Move_HotDll():
    # 定义源文件路径和目标文件夹路径
    source_file = r"D:\Project\HotFix_Test\HybridCLR_Project\HybridCLRData\HotUpdateDlls\StandaloneWindows64\HotUpdate.dll"  # 替换为实际源文件路径
    target_dir = r"D:\Project\HotFix_Test\HybridCLR_Project\Build\HybridCLR_ProJect_Data\StreamingAssets"            # 替换为目标文件夹路径

    # 确保目标文件夹存在，不存在则创建 <button class="citation-flag" data-index="6"><button class="citation-flag" data-index="7">
    os.makedirs(target_dir, exist_ok=True)

    # 构造新文件名并执行复制 <button class="citation-flag" data-index="8"><button class="citation-flag" data-index="10">
    new_filename = "HotUpdate.dll" + ".bytes"
    target_path = os.path.join(target_dir, new_filename)
    shutil.copy(source_file, target_path)

    os.system(f"explorer.exe {target_dir}")

    print(f"文件已复制到: {target_path}")

def open_exe():
    """
    打开指定路径的exe文件
    
    Args:
        exe_path (str): exe文件的完整路径
    
    Returns:
        bool: 是否成功启动程序
    """
       # 替换为你的exe文件路径
    exe_path = r"D:\Project\HotFix_Test\HybridCLR_Project\Build\HybridCLR_Project.exe"
    try:
        # 检查文件是否存在
        if not os.path.exists(exe_path):
            print(f"错误：文件 {exe_path} 不存在！")
            return False
        
        # 使用subprocess启动程序
        subprocess.Popen(exe_path)
        print(f"成功启动程序：{exe_path}")
        return True
        
    except Exception as e:
        print(f"启动程序时发生错误：{str(e)}")
        return False

def kill_unity_process():
    try:
        # 使用taskkill命令强制结束所有Unity进程
        subprocess.run(['taskkill', '/F', '/IM', 'Unity.exe'], 
                      capture_output=True, 
                      text=True)
        print("已关闭所有Unity进程")
        return True
    except Exception as e:
        print(f"关闭Unity进程时出错：{str(e)}")
        return False



if __name__ == "__main__":
    print("开始编译HybridCLR DLL之前先关闭Unity")
    while True:
        choice = input("是否关闭Unity进程？(y/n): ").lower()
        if choice in ['y', 'n']:
            break
        print("请输入 y 或 n")
    
    if choice == 'y':
        kill_unity_process()
        print("等待Unity进程完全关闭...")
        time.sleep(2)

    result = Build_HotDll()
    print(f"Build_HotDll 返回值: {result}")
    if result:
        print("--------------------------------")
        Move_HotDll()
        print("--------------------------------")
        open_exe()

input("按任意键继续...")
